package com.llg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llg.mapper.LedBrandMapper;
import com.llg.model.BrandModel;
import com.llg.model.code.CommonCode;
import com.llg.model.code.PageCode;
import com.llg.model.response.*;
import com.llg.pojo.LedBrand;
import com.llg.util.Entity2Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;


@Service
public class LedBrandService {

    @Autowired
    private LedBrandMapper brandMapper;

    //查询所有品牌
    public PageResult<BrandModel> findAll() {
        List<LedBrand> brands = brandMapper.selectAll();
        List<BrandModel> models = new ArrayList<>();
        for (LedBrand brand : brands) {
            models.add(Entity2Model.brand2Model(brand));
        }
        PageResult pageResult = new PageResult(CommonCode.SUCCESS, 1, 1, models);
        return pageResult;
    }

    //搜索并分页查询
    public PageResult<BrandModel> findPage(int currentPage, int pageSize, LedBrand ledBrand) {
        //判断参数是否合法
        if (currentPage <= 0) return new PageResult<>(PageCode.PAGE_ERR1, 0, 0, null);
        if (pageSize <= 0) return new PageResult<>(PageCode.SIZE_ERR, 0, 0, null);
        PageHelper.startPage(currentPage, pageSize);
        Example example = new Example(LedBrand.class);
        Example.Criteria criteria = example.createCriteria();
        if (ledBrand != null) {
            if (ledBrand.getName() != null && !ledBrand.getName().equals("")) {
                criteria.andLike("name", "%" + ledBrand.getName() + "%");
            }
        }
        List<LedBrand> list = brandMapper.selectByExample(example);
        PageInfo<LedBrand> page = new PageInfo<>(list);
        List<LedBrand> brands = page.getList();
        List<BrandModel> models = new ArrayList<>();
        for (LedBrand brand : brands) {
            models.add(Entity2Model.brand2Model(brand));
        }
        return new PageResult<>(CommonCode.SUCCESS, (int) page.getTotal(), page.getPages(), models);
    }

    //根据id查询品牌信息
    public DataResult<BrandModel> findById(Integer id) {
        LedBrand brand = brandMapper.selectByPrimaryKey(id);
        return new DataResult<>(CommonCode.SUCCESS, Entity2Model.brand2Model(brand));
    }

    //添加品牌
    public DataResult<BrandModel> save(LedBrand brand) {
        brandMapper.insertSelective(brand);
        return new DataResult<>(CommonCode.SUCCESS, Entity2Model.brand2Model(brand));
    }

    //删除品牌
    public ResponseResult remove(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //修改品牌信息
    public ResponseResult update(LedBrand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
        return new ResponseResult(CommonCode.SUCCESS);
    }

}
